package reader

import (
	"errors"

	"github.com/wzh200x/gateServer/network/message"
)

type PacketReader struct {
	HeaderCodec *HeaderCodec
	Header      *message.Header
	ReadSize    int
}

func NewPacketReader() *PacketReader {
	return &PacketReader{
		HeaderCodec: &HeaderCodec{},
		Header:      message.NewHeader(),
	}
}

func (this *PacketReader) GetHeader() *message.Header {
	return this.Header
}

func (this *PacketReader) Reader(datas []byte) (error, *message.Packet) {
	if this.Header.Length == -1 && len(datas) >= message.HeaderSize {
		headDatas := datas[:message.HeaderSize]
		err := this.HeaderCodec.Decode(headDatas, this.Header)
		if err != nil {
			return err, nil
		}
		this.ReadSize += message.HeaderSize
	}
	if this.Header.Length >= 0 {
		if this.Header.Length > message.MaxBodySize {
			return errors.New("packet size too large"), nil
		}
		if len(datas)-message.HeaderSize >= int(this.Header.Length) {
			bodyDatas := datas[message.HeaderSize : message.HeaderSize+int(this.Header.Length)]
			opcode := this.Header.Opcode
			packet := message.NewPacket(opcode)
			packet.Datas = bodyDatas
			packet.Size = this.Header.Length
			this.ReadSize += int(this.Header.Length)
			this.Header.Reset()
			return nil, packet
		} else {
			return nil, nil
		}
	}
	return errors.New("reader packet failed"), nil
}

func (this *PacketReader) Reset() {
	this.ReadSize = 0
}
